package cn.zn.quartz.job;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.zn.base.common.constant.Constants;
import cn.zn.base.common.constant.ScheduleConstants;
import cn.zn.base.common.enums.BusinessStatus;
import cn.zn.base.common.utils.SpringContextUtil;
import cn.zn.base.exception.CustomException;
import cn.zn.quartz.dto.JobDto;
import cn.zn.quartz.dto.JobLogDto;
import cn.zn.quartz.service.JobService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 抽象quartz调用
 *
 * @author zn-admin
 */
@Component
public abstract class AbstractQuartzJob implements Job {

    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static ThreadLocal<LocalDateTime> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDto job = new JobDto();
        BeanUtil.copyProperties(context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES), job);
        try {
            before(context, job);
            doExecute(context, job);
            after(context, job, null);
        } catch (Exception e) {
            log.error("任务执行异常  - ：" + e.toString());
            if (threadLocal.get() == null) {
                threadLocal.set(LocalDateTime.now());
            }
            after(context, job, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param job     系统计划任务
     */
    protected void before(JobExecutionContext context, JobDto job) {
        threadLocal.set(LocalDateTime.now());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     * @param job     系统计划任务
     */
    protected void after(JobExecutionContext context, JobDto job, Exception e) {
        LocalDateTime startTime = threadLocal.get();
        threadLocal.remove();

        final JobLogDto jobLog = new JobLogDto();
        jobLog.setJobId(job.getId());
        jobLog.setJobName(job.getJobName());
        jobLog.setJobGroup(job.getJobGroup());
        jobLog.setInvokeTarget(job.getInvokeTarget());
        LocalDateTime stopTime = LocalDateTime.now();
        long runMs = stopTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli() - startTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        jobLog.setJobMessage(jobLog.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null) {
            jobLog.setStatus(BusinessStatus.FAIL.getCode());

            String errorMsg;
            if (e instanceof CustomException) {
                errorMsg = e.getMessage();
            } else {
                errorMsg = ExceptionUtil.stacktraceToString(e);
            }

            jobLog.setExceptionInfo(errorMsg);
        } else {
            jobLog.setStatus(Constants.SUCCESS);
        }

        // 写入数据库当中
        SpringContextUtil.getBean(JobService.class).insertJobLog(jobLog);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, JobDto job) throws Exception;
}
